﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Text;
using System.Windows.Forms;

using RollBackLib.src.utils;
using RollBackLib.src.core;

namespace RollBack.src.ui
{
    public partial class BackupDestinationPanel : UserControl
    {
        private System.EventHandler m_startButtonClickHandler;
        private System.EventHandler m_pauseButtonClickHandler;
        private System.EventHandler m_advancedButtonClickHandler;

        public BackupDestinationPanel()
        {
            InitializeComponent();
            m_runStatsView.reduceHeaderFontSize();
        }

        private void StartButtonClick(object sender, EventArgs e)
        {
            if (m_startButtonClickHandler != null)
            {
                m_startButtonClickHandler(sender, e);
            }
        }

        /// <summary>
        /// Set the handlers for start,stop,pause and advanced buttons
        /// </summary>
        /// <param name="startButton"></param>
        /// <param name="stopButton"></param>
        /// <param name="pauseButton"></param>
        /// <param name="advancedButtonClickHandler"></param>
        public void setButtonHandlers(EventHandler startButton,
            EventHandler pauseButton,
            EventHandler advancedButtonClickHandler)
        {
            m_startButtonClickHandler = startButton;
            m_pauseButtonClickHandler = pauseButton;
            m_advancedButtonClickHandler = advancedButtonClickHandler;
        }

        /// <summary>
        /// Updates the status and changes the progress indicator
        /// </summary>
        /// <param name="status"></param>
        /// <param name="value">By how much to increase the progress indicator</param>
        public void updateStatus(string status, BackupInfo binfo, int progressIndicatorStep, bool runStatusChanged)
        {
            m_statusText.Text = status;
            m_statusText.Select(0, 0);

            if (binfo != null)
            {
                if (binfo.m_Statistics.m_operation != CurrentOperation.InPause)
                {
                    long diff = (DateTime.Now.Ticks - m_progressIndicatorLastUpdate.Ticks) / (1000);
                    if (runStatusChanged)
                    {
                        changeButtonStates(binfo.m_Job.m_RunningStatus);
                    }
                    updateDestinationPanelStats(status, binfo);
                    if (progressIndicatorStep > 0 && (diff > 300))
                    {
                        m_progressIndicatorLastUpdate = DateTime.Now;
                        int range = m_progressIndicator.Maximum - m_progressIndicator.Minimum;
                        int nv = m_progressIndicator.Value + progressIndicatorStep;
                        if (nv > m_progressIndicator.Maximum)
                        {
                            nv = m_progressIndicator.Minimum;
                        }
                        m_progressIndicator.Value = nv;
                    }
                }
            }
            else
            {
                // set the default values for the buttons in the destination panel
                changeButtonStates(BackupInfo.RunStatus.NotRunning);
            }
        }

        /// <summary>
        /// Enable the progress indicator and change the progress style to marquee
        /// </summary>
        private void startProgressIndicator()
        {
            m_progressIndicator.ForeColor = Color.Green;
            m_progressIndicator.Style = ProgressBarStyle.Marquee;
            m_progressIndicator.Maximum = 100;
            m_progressIndicator.Step = 1;
            m_progressIndicator.Visible = true;
            m_progressIndicator.Value = 40;
        }

        /// <summary>
        /// Update the status text and the file/folder listview counters.
        /// </summary>
        /// <param name="status"></param>
        /// <param name="binfo"></param>
        private void updateDestinationPanelStats(string status, BackupInfo binfo)
        {

            // got a callback when backup job is running
            long diff2 = (DateTime.Now.Ticks - m_lastUpdateTime.Ticks);
            diff2 /= 10000;
            if (diff2 > 200)
            {
                m_lastUpdateTime = DateTime.Now;
                m_statusText.Text = status;
                BackupStatistics stats = binfo.m_Statistics;
                // create the statistics message about the backup operation
                long totalFileScannedBytes = stats.m_fileStats.m_inProgress + stats.m_fileStats.m_totalBytesScanned;
                long totalFileCopiedBytes = stats.m_fileStats.m_totalBytesCopied;
                string statistics_msg =
                    string.Format("Dirs: [{0,-5:D}]  Files: [{1,-6:D}]  Copied: [{2:%s} of {3:%s}]   Total: [{4:%s}],   TotalScanned: [{5:%s}]",
                    stats.m_dirStats.m_copied + stats.m_dirStats.m_created,
                    stats.m_fileStats.m_copied + stats.m_fileStats.m_skipped,
                    AppUtils.toHumanReadableSize(stats.m_fileStats.m_inProgress),
                    AppUtils.toHumanReadableSize(stats.m_fileStats.m_currentSize),
                    AppUtils.toHumanReadableSize(totalFileCopiedBytes),
                    AppUtils.toHumanReadableSize(totalFileScannedBytes));
                m_runStatsView.addToJobRunStats(stats);
            }
        }

        /// <summary>
        /// Stop the progress indicator in response to stopping the backup operation.
        /// </summary>
        private void stopProgressIndicator()
        {
            this.m_progressIndicator.Minimum = 1;
            this.m_progressIndicator.Maximum = 1;
            this.m_progressIndicator.Value = 1;
            this.m_progressIndicator.Style = ProgressBarStyle.Blocks;
            m_progressIndicator.Visible = true;
        }

        /// <summary>
        /// Change the start/stop/pause button states depending on whether the backup is already running or not.
        /// <param name="toggle">if enable is truen then stop/pause buttons are enabled and start button is disabled.
        /// Set to false for the reverse</param>
        /// </summary>
        private void changeButtonStates(BackupInfo.RunStatus status)
        {
            switch (status)
            {
                case BackupInfo.RunStatus.NotRunning:
                    m_startButton.Text = " Start ";
                    m_stopButton.Enabled = false;
                    m_advancedButton.Enabled = true;
                    m_startButton.ImageIndex = ImageResources.Indexes.m_playButtonImage;
                    stopProgressIndicator();
                    break;
                case BackupInfo.RunStatus.Paused:
                    m_stopButton.Enabled = true;
                    m_startButton.Text = " Resume ";
                    m_startButton.ImageIndex = ImageResources.Indexes.m_playButtonImage;
                    pauseProgressIndicator();
                    break;
                case BackupInfo.RunStatus.Running:
                    m_startButton.Text = " Pause ";
                    m_stopButton.Enabled = true;
                    m_advancedButton.Enabled = false;
                    m_startButton.ImageIndex = ImageResources.Indexes.m_pauseButtonImage;
                    startProgressIndicator();
                    break;
            }
        }

        private void pauseProgressIndicator()
        {
            m_progressIndicator.Style = ProgressBarStyle.Continuous;
            m_progressIndicator.BackColor = Color.Orange;
            m_progressIndicator.ForeColor = Color.Orange;
        }
    }
}
